package glemipsc.implementations.glemips32;

import glemipsc.Address;
import glemipsc.GLEMipsC;
import glemipsc.GLEMipsEmu;
import glemipsc.implementations.Argument;
import glemipsc.implementations.Instruction;
import glemipsc.implementations.Implementation;

public class Jal extends Instruction {
	
	public Jal(Argument arg) {
		arguments.add(arg);
	}
	
	@Override
	public String getOpCode() {
		String opcode = Instruction.JAL;
		
		if (arguments.get(0) instanceof Register) {
			// Register
			opcode += arguments.get(0).getOpCode();
			opcode += zeros(21);
		}
		else {
			// Immediate or Address
			opcode += arguments.get(0).getOpCode();
			opcode += zeros(10);
		}
		return opcode + "\n";
	}

	@Override
	public String getName() {
		return "JAL";
	}

	@Override
	public void emulate(GLEMipsEmu emu) {
		Implementation impl = emu.getImplementation();
		((Register) impl.getReturnRegister()).setEmulValue(emu.getPC() + 1);
		if (arguments.get(0) instanceof Register)
			emu.setPC(((Register) arguments.get(0)).getEmulValue());
		else
			emu.setPC(((Address) arguments.get(0)).getValue());
	}

}
